package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author lzq
 * @data 2023/4/26 20:24
 */
@Component
@Slf4j
//全局过滤器
public class AuthorizeFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //1判断是否是登录
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if (request.getURI().getPath().contains("/login")){
            //包含login登录放行
           return chain.filter(exchange);
        }
        //2不是登录,获取token
        String token = request.getHeaders().getFirst("token");
        //3判断是否携带token
        if (StringUtils.isBlank(token)){
            //不携带,返回状态码  HttpStatus.UNAUTHORIZED(401)
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4携带token判断token是否正确有效 (解析token可能出异常,需要try)
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int num = AppJwtUtil.verifyToken(claims);
            if (num==1||num==2){
                //token过期   HttpStatus.UNAUTHORIZED(401)
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //获得token解析后中的用户信息
            Object userId = claims.get("id");
            //在header中添加新的信息
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();
            //重置header
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //token正确可以使用,放行
        return chain.filter(exchange);
    }


    //设置优先级,越小越优先
    @Override
    public int getOrder() {
        return 0;
    }
}
